package com.moyu.common.redis.service;

import com.moyu.common.core.constants.CacheConstants;
import com.moyu.common.core.utils.RandomTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 分布式Redis锁
 *
 * @Author 赵彦博
 * @Date 2024/12/30 13:59
 */
@Slf4j
@Component
public class RedissonLockService {

    @Autowired
    private RedissonClient redissonClient;

    private static Long lockTime;

    // 加锁，并返回获取到的锁对象
    public RLock lock(String lockName) {
        if (redissonClient == null) {
            log.info("RedissonLockService redissonClient is null");
            return null;
        }
        lockTime = RandomTimeUtils.randomTime(CacheConstants.LOCK_EXP,TimeUnit.SECONDS);
        try {
            RLock lock = redissonClient.getLock(lockName);
            // 锁10秒后自动释放，防止死锁
            lock.lock(lockTime, TimeUnit.SECONDS);

            log.info("Thread [{}] RedissonLockService 获取锁成功", Thread.currentThread().getName(), lockName);
            return lock;
        } catch (Exception e) {
            log.error("RedissonLockService 获取锁失败:", lockName, e);
            return null;
        }
    }

    // 使用传入的锁对象进行解锁
    public Boolean unlock(RLock lock) {
        if (lock == null) {
            return false;
        }

        try {
            lock.unlock();
            log.info("Thread [{}] RedissonLockService 释放锁成功", Thread.currentThread().getName());
            return true;
        } catch (Exception e) {
            log.error("RedissonLockService 释放锁失败:", e);
            return false;
        }
    }
}
